package br.com.virtual.base.converter;

import java.util.GregorianCalendar;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.inject.Named;

import org.primefaces.component.calendar.Calendar;

import br.com.virtual.base.uteis.VirtualConverter;

@Named("calendarConverter")
public class CalendarConverter implements Converter {

	@Override
	public Object getAsObject(FacesContext ctx, UIComponent cmp, String str) {
		try {
			if (cmp instanceof Calendar) {
				return VirtualConverter.getDate(str,
						((Calendar) cmp).getPattern());
			} else {
				if (cmp.getAttributes().get("pattern") != null)
					return VirtualConverter.getDate(str, cmp.getAttributes()
							.get("pattern").toString());
				else {
					return VirtualConverter.getDate(str, "dd/MM/yyyy");
				}
			}
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	public String getAsString(FacesContext ctx, UIComponent cmp, Object obj) {
		if (cmp instanceof Calendar) {
			return obj != null ? VirtualConverter.getStrDate(
					(GregorianCalendar) obj, ((Calendar) cmp).getPattern())
					: null;
		} else {
			if (cmp.getAttributes().get("pattern") != null)
				return obj != null ? VirtualConverter.getStrDate(
						(GregorianCalendar) obj,
						cmp.getAttributes().get("pattern").toString()) : null;
			else {
				System.out
						.println("Calendar Converter necessita do atributo pattern \"<f:attribute name=\"pattern\" value=\"dd/MM/yyyy\" /> ");
				return obj != null ? VirtualConverter.getStrDate(
						(GregorianCalendar) obj, "dd/MM/yyyy") : null;
			}

		}
	}
}
